﻿package com.mulder.study.netty.server;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;

import com.mulder.study.netty.ErrorHandler;
import com.mulder.study.netty.MulderNettyBootStrap;


/**
 * Netty 를 이용하는 전형적인 아주 단순한 Server 템플릿.
 * 
 * @author mulder
 */
public class MulderNettyCommonServer {
	private static final Logger logger = Logger.getLogger(MulderNettyCommonServer.class);
	
	public boolean running = false;
	public boolean connected = false;

	private SocketAddress socketAddress;
	private ChannelHandler channelHandler;
	private ErrorHandler errorHandler;
	
	private Thread thread;
	
	private MulderNettyBootStrap bootStrap = new MulderNettyBootStrap(true);               
        
	
	/**
	 * 생성자 
	 * 
	 */
	public MulderNettyCommonServer(int bindPort
			, ChannelHandler channelHandler, ErrorHandler errorHandler, boolean runThread) 
	{
		super();
		this.socketAddress = new InetSocketAddress(bindPort);
		this.channelHandler = channelHandler;
		this.errorHandler = errorHandler;
		
		if(runThread)
		{
		    thread = new Thread(new Runnable () 
		    {
                        @Override
                        public void run()
                        {
                            logger.info("Thread run Enter !");
                           execute();
                        }
		        
		    });
	            thread.start();    
		}
		
		logger.info("MulderNettyCommonClient target => "+this.socketAddress.toString());
	}
	

	/**
	 * 쓰레드 메인.
	 * 
	 */
	public void execute() 
	{
		this.running = true;
		logger.info("MulderNettyCommonServer Execute Enter !!!");

		try {
			bootStrap.getBootStrap().setPipelineFactory(new ChannelPipelineFactory() {

				public ChannelPipeline getPipeline() throws Exception {
					return Channels.pipeline(channelHandler);
				}
			});
			
			Channel bindChannel = ((ServerBootstrap)(bootStrap.getBootStrap())).bind(socketAddress);
			logger.info( "MulderNettyCommonServer Running !!!");
			
			Runtime.getRuntime().addShutdownHook(new Thread() 
			{
                            @Override
                            public void run()
                            {
                                running = false;
                                bootStrap.releaseExternalResources();
                                
                                logger.info( "MulderNettyCommonServer Execute Exit !!!");
                                
                            }
			});
			
		} 
		finally
		{
			
		}
	}
	
	
}